package cn.com.pajx.pajx_visitor_v3.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.pajx.pajx_visitor_v3.R;
import cn.com.pajx.pajx_visitor_v3.base.BaseActivity;
import cn.com.pajx.pajx_visitor_v3.base.BaseMvpFragment;
import cn.com.pajx.pajx_visitor_v3.bean.AppBean;
import cn.com.pajx.pajx_visitor_v3.mvp.presenter.LoadDataPresenterImpl;
import cn.com.pajx.pajx_visitor_v3.utils.UpdateUtil;

/**
 * 更新App
 * create an instance of this fragment.
 */
@SuppressLint("NonConstantResourceId")
public class UpdateAppFragment extends BaseMvpFragment<LoadDataPresenterImpl> {

    private static final String ARG_APP_BEAN = "APP_BEAN";
    @BindView(R.id.tv_update_des)
    TextView tvUpdateDes;
    @BindView(R.id.iv_close)
    ImageView ivClose;


    private AppBean appBean;

    public UpdateAppFragment() {
    }

    public static UpdateAppFragment newInstance(AppBean appBean) {
        UpdateAppFragment fragment = new UpdateAppFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_APP_BEAN, appBean);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void beforeInitHead() {
        super.beforeInitHead();
        assert getArguments() != null;
        appBean = getArguments().getParcelable(ARG_APP_BEAN);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_update_app;
    }

    @Override
    protected double loadWidthScale() {
        return 0.6;
    }

    @Override
    protected LoadDataPresenterImpl initPresenter() {
        return new LoadDataPresenterImpl();
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        if (appBean != null) {
            tvUpdateDes.setText(appBean.getUp_desc());
            if (!appBean.isForce_update())
                ivClose.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.iv_close, R.id.tv_update})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                dismiss();
                break;
            case R.id.tv_update:
                dismiss();
                if (appBean != null && !TextUtils.isEmpty(appBean.getDownload_url()))
                    UpdateUtil.getInstant().updateApk((BaseActivity) requireActivity(), appBean, mContext.getPackageManager());
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086) {
            //安装apk
            UpdateUtil.getInstant().installProcess((BaseActivity) requireActivity(), mContext.getPackageManager());
        }
    }
}